﻿; if (!Number.prototype.toFixed) {
    Number.prototype.toFixed = function (precision) {
        var power = Math.pow(10, precision || 0);
        return Math.round(this * power) / power;
    }
}

(function ($, window, document, undefined) {
    
    //Annotations

    function AnnotationComment(id, annotationId, commentText){
        this.id = ko.observable(id);
        this.annotationId = ko.observable(annotationId);
        this.commentText = ko.observable(commentText);
    }

    function Annotation(id, entityId, entityTypeParameter, x, y, z, isMinimized, annotationText) {
        this.id = ko.observable(id);
        this.entityId = ko.observable(entityId);
        this.entityTypeParameter = ko.observable(entityTypeParameter);
        this.x = ko.observable(x);
        this.y = ko.observable(y);
        this.z = ko.observable(z);
        this.isMinimized = ko.observable(isMinimized);
        this.annotationText = ko.observable(annotationText);
        this.comments = ko.observableArray([]);
    }
    
    var viewModel = {
        annotations: ko.observableArray([]),
        annotationsForDelete: ko.observableArray([]),
        commentsForDelete: ko.observableArray([]),
        currentAnnotationId: ko.observable(),
        currentAnnotationCommentId: ko.observable(),
        
        addAnnotation: function(id, entityId, entityTypeParameter, x, y, z, notes) {              
            var annotation = new Annotation(id, entityId, entityTypeParameter, x, y, z, false, notes);
            this.annotations.push(annotation);   
        },

        saveAnnotationText: function(id, annotationText){            
            this.currentAnnotationId(id);                    
            var current = this.currentAnnotation();
            if(current != null){        
                current.annotationText(annotationText);
            }
        },

        removeAnnotation: function(id){
            this.currentAnnotationId(id);                    
            var current = this.currentAnnotation();
            if(current != null){                    
                this.annotations.remove(current);
                this.annotationsForDelete.push(id);
            }
        },

        addComment: function(id, annotationId, commentText){
            this.currentAnnotationId(annotationId);                    
            var current = this.currentAnnotation();
            if(current != null){ 
                var comment = new AnnotationComment(id, annotationId, commentText);
                current.comments.push(comment);
            }
        },

        saveCommentText: function(id, commentText){
            this.currentAnnotationCommentId(id);
            var current = this.currentAnnotationComment();
            if(current != null){                 
                current.commentText(commentText);
            }
        },

        removeComment: function(id){
            this.currentAnnotationCommentId(id);
            var current = this.currentAnnotationComment();
            if(current != null){
                this.currentAnnotationId(current.annotationId());
                var currentAnnotation = this.currentAnnotation(); 
                if(currentAnnotation != null){
                    currentAnnotation.comments.remove(current);
                    this.commentsForDelete.push(id);                    
                }
            }
        },

        toServer: function (entityId, entityTypeParameter, annotationElementFormat, annotationCommentElementFormat, url, callback) {
            var items = ko.toJS(this.annotations()); 
            var forDeleteItems = ko.toJS(this.annotationsForDelete()); 
            var forDeleteComments = ko.toJS(this.commentsForDelete()); 
            var mappedItems = ko.utils.arrayMap(items, function (item) {
                if(annotationElementFormat){
                    item.id = item.id.toString().replace(annotationElementFormat, '');
                }
                item.x = coordinateTransform(item.x.toString().replace('px', ''));
                item.y = item.y.toString().replace('px', '');
                item.comments = ko.utils.arrayMap(item.comments, function (comment) {
                    if(annotationCommentElementFormat){
                        comment.id = comment.id.toString().replace(annotationCommentElementFormat, '');
                    }
                    if(annotationElementFormat){
                        comment.annotationId = comment.annotationId.toString().replace(annotationElementFormat, '');
                    }
                    return comment;
                });
                delete item.entityId;
                return item;
            });
            var mappedForDeleteItems = ko.utils.arrayMap(forDeleteItems, function (item) {
                if(annotationElementFormat){
                    item = item.toString().replace(annotationElementFormat, '');
                }
                return item;
            }); 
            var mappedForDeleteComments = ko.utils.arrayMap(forDeleteComments, function (item) {
                if(annotationCommentElementFormat){
                    item = item.toString().replace(annotationCommentElementFormat, '');
                }
                return item;
            }); 
            $.ajax({
                type: 'POST',
				async: false,
                url: url,
                data: JSON.stringify({EntityId:entityId, EntityTypeParameter: entityTypeParameter, Notes: mappedItems, AnnotationsForDelete: mappedForDeleteItems, CommentsForDelete: mappedForDeleteComments}),
                success: function (data) {
                    if(callback){
                        callback(data.result, data.url);
                    }
                },
                contentType: 'application/json, charset=utf-8',
                dataType: 'json'
            });
        }
    };

    viewModel.annotationCount =  ko.dependentObservable(function () {
        return this.annotations().length;
    }, viewModel);

    viewModel.commentCount =  ko.dependentObservable(function () {
        var _count = 0;
        ko.utils.arrayForEach(this.annotations(), function(item) {               
            _count += item.comments().length;
        });
        return _count;
    }, viewModel);

    viewModel.entityId = ko.dependentObservable(function () {
        var _entityId = 0;
        ko.utils.arrayForEach(this.annotations(), function(item) {               
            _entityId = item.entityId();
        });
        return _entityId;
    }, viewModel);
    
    viewModel.entityTypeParameter = ko.dependentObservable(function () {
        var _entityTypeParameter = '';
        ko.utils.arrayForEach(this.annotations(), function(item) {               
            _entityTypeParameter = item.entityTypeParameter();
        });
        return _entityTypeParameter;
    }, viewModel);

    viewModel.currentAnnotation = ko.dependentObservable(function() {
        var search = this.currentAnnotationId();
        if (!search) {
            return null;
        } else {
            return ko.utils.arrayFirst(this.annotations(), function(item) {
                return item.id() == search;
            });
        }
    }, viewModel);

    viewModel.currentAnnotationComment = ko.dependentObservable(function() {
        var search = this.currentAnnotationCommentId();
        if (!search) {
            return null;
        } else {
            var _current;
            ko.utils.arrayForEach(this.annotations(), function(item) {
                var _iteratedComment = ko.utils.arrayFirst(item.comments(), function(comment) {   
                    return comment.id() == search;
                });
                if(_iteratedComment){
                    _current = _iteratedComment;
                }
            });
            return _current;  
        }
    }, viewModel);

    ko.applyBindings(viewModel);
    
    //Plugin definition
    var pluginName = 'stickyNotes',
        defaults = {
            forEntityIdElement: '',
            forEntityTypeParameterElement: '',
            annotationElementFormat: '',
            addNewAnnotationElement: '',
            addNewAnnotationProto: '',
            annotationContainerElement: '',
            saveAnnotationsElement: '',
            saveAnnotationsUrl: '',
            saveAnnotationsCallback: '',
            addNewAnnotationCommentElement: '',
            annotationCommentElementFormat: '',
            addNewAnnotationCommentProto: '',
            annotationCommentContainerFormat: ''
        },
        _options;

    function Plugin(elements, options) {  
        this.init(elements, defaults, options);
    }

    Plugin.prototype.init = function (elements, defaults, options) { 
        this.options = $.extend({}, defaults, options);

        _options = this.options;

        var $elements = $(elements).children();
        makeDraggable($elements/*.find('.b-sticker__head')*/);
        
        var entityId;
        var entityTypeParameter;
        
        if(options.forEntityIdElement){
            entityId = $(options.forEntityIdElement).val();
        }
        else{
            entityId = 0;
        }
        
        if(options.forEntityTypeParameterElement) {
            entityTypeParameter = $(options.forEntityTypeParameterElement).val();
        }
        else {
            entityTypeParameter = '';
        }

        $elements.each(function(){
            var $el = $(this);
            $el.css('left', Number(reverseCoordinateTransform($el.css('left').toString().replace('px', ''))));
            $el.css('z-index', 99999);
            
            var annotationId = $el.attr("id");
            viewModel.addAnnotation(annotationId, entityId, entityTypeParameter, $el.css('left'), $el.css('top'), $el.css('z-index'), $el.find('.b-sticker__annotation span').text());

            $el.find('.b-sticker__comment').each(function(){
               var $commentEl = $(this);
               viewModel.addComment($commentEl.attr('id'), annotationId, $commentEl.find('.b-sticker__comment__text span').text()); 
            });            
        });

        if(options.saveAnnotationsElement){            
            $(options.saveAnnotationsElement).click(function(){               
               if(options.saveAnnotationsUrl){
                   viewModel.toServer(viewModel.entityId(), viewModel.entityTypeParameter(), options.annotationElementFormat, options.annotationCommentElementFormat, options.saveAnnotationsUrl);
                   if(options.saveAnnotationsCallback){
                        options.saveAnnotationsCallback();
                   }
               }
            });
        }

        if(options.addNewAnnotationElement){            
            $(options.addNewAnnotationElement).click(function(){                
                if(options.addNewAnnotationProto && options.annotationContainerElement){
                    var $proto = $(options.addNewAnnotationProto);
                    var $container = $(options.annotationContainerElement);
                    if($proto && $container){
                        var $new = $proto.clone();                        
                        $new.show().appendTo($container);
                        var annotationId = (-1) * viewModel.annotationCount();
                        
                        $new.attr("id", options.annotationElementFormat + annotationId);
                        $new.css('z-index', 99999);
                        $new.addClass('b-note');
                        $new.css('position','absolute');
                        $new.css('top',0);

                        $new.find('.b-sticker__delete').attr('data-annotations-id', annotationId);
                        $new.find('.b-sticker__annotation span').attr('data-annotations-text', annotationId);

                        makeDraggable($new);
                       
                        viewModel.addAnnotation($new.attr("id"), entityId, entityTypeParameter, $new.css('left'), $new.css('top'), $new.css('z-index'), '');
                    }
                }
            });
        }
        
        if(options.addNewAnnotationCommentElement){
            $(options.addNewAnnotationCommentElement).live('click', function(){
                var $el = $(this);
                if(options.addNewAnnotationCommentProto && options.annotationCommentContainerFormat){ 
                    var $proto = $(options.addNewAnnotationCommentProto);
                    var annotationId = $el.data('annotations-id');
                    var $container = $(options.annotationCommentContainerFormat + annotationId);
                    var commentWidth = ($container.parent())[0].scrollWidth -50;
                    if($proto && $container  && !($container.find('.annotation-comment-editable').length>0)){
                        var $new = $proto.clone();

                        $new.show().appendTo($container);
                        var commentId = (-1) * viewModel.commentCount();


                        $new.find('.b-sticker__comment__delete').attr('data-annotation-comment-id', commentId);
                        $new.find('.b-sticker__comment__text span').attr('data-annotation-comment-text', commentId);

                        commentId = options.annotationCommentElementFormat + commentId;

                        $new.attr('id', commentId);

                        viewModel.addComment(commentId, options.annotationElementFormat + annotationId, '');
                        $new.find('.annotation-comment-editable').css('width',commentWidth);
                    }
                }                
            });
        }    
    };

    Plugin.prototype.SaveAnnotationText = function(annotationId, annotationText){        
        viewModel.saveAnnotationText(_options.annotationElementFormat + annotationId, annotationText);   
    };

    Plugin.prototype.DeleteAnnotation = function(annotationId){        
        viewModel.removeAnnotation(_options.annotationElementFormat + annotationId);   
    };

    Plugin.prototype.SaveCommentText = function(commentId, commentText){        
        viewModel.saveCommentText(_options.annotationCommentElementFormat + commentId, commentText);   
    };

    Plugin.prototype.DeleteComment = function(commentId){        
        viewModel.removeComment(_options.annotationCommentElementFormat + commentId);   
    };

    $.fn[pluginName] = function (options) {
        var extraArgs;
        extraArgs = Array.prototype.slice.call(arguments, 1);
        return this.each(function () {
            var plugin;
            if(typeof options === "string"){
                plugin = $.data(this, 'plugin_' + pluginName);
                if(plugin){
                    plugin[options].apply(plugin, extraArgs);
                }            
            } else if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin(this, options));
            }
        });
    }

    //additional functions
    function makeDraggable($el){
        if($el){
            $el.draggable({
                stop: function (event, ui) {
                    viewModel.currentAnnotationId(ui.helper.attr('id'));
                    var current = viewModel.currentAnnotation();
                    if(current != null){                    
                        current.x(ui.position.left);
                        current.y(ui.position.top);
                        current.z(ui.helper.css("z-index"));
                    }
                },
                handle: '.b-sticker__head'
            });
        }
    }

    function coordinateTransform(left){
        left = Number(left);

        var newCenter;
        if($(window).width()>940){
            newCenter = Number(($(window).width()/2).toFixed());
        }
        else{
            newCenter = 470;
        }
        var result = Number(((-1) * newCenter + left)).toFixed();
        return result;
    }

    function reverseCoordinateTransform(left){
        left = Number(left);
        var newCenter;
        if($(window).width()>940){
            newCenter  = Number(($(window).width()/2).toFixed());
        }
        else{
            newCenter = 470;
        }
        var result = Number((newCenter + left)).toFixed();
        return result;
    }

    function log(message) {
        if (window.console && window.console.log){
            window.console.log(message);
        }
    };

})(jQuery, window, document);

$(document).ready(function () {
    var $stickyNotes = $('#stickyNotesPanel').stickyNotes({
        forEntityIdElement: '#stickyNotes-entityid',
        forEntityTypeParameterElement: '#stickyNotes-entitytypeparameter',
        annotationElementFormat: 'annotation_',
        addNewAnnotationElement: '#cms-js-add-annotation',
        addNewAnnotationProto: '#stickyNotesProto',
        annotationContainerElement: '#stickyNotesPanel',
        saveAnnotationsElement: '#cms-js-save-annotation',
        saveAnnotationsUrl: '/admin/cmspage/saveentityannotations',
        addNewAnnotationCommentElement: '.b-sticker__add',
        annotationCommentElementFormat: 'annotation_comment_',
        addNewAnnotationCommentProto: '#stickyNotesCommentProto',
        annotationCommentContainerFormat: '#annotation_comment_container_',
        saveAnnotationsCallback: function () {
            parent.$.fancybox.close();
        }
    });

    $('.b-sticker__edit').live('click', function () {
        var sticky = $(this).parents('.b-note');
        var annotationText = sticky.find('.b-sticker__annotation span');
        var textArea = $('<textarea class="annotation-editable text">' + annotationText.text() + '</textarea>');
        textArea.css({
            'width': sticky.find('.b-sticker__body')[0].scrollWidth - 30 + 'px'
        });

        var annotation = sticky.find('.b-sticker__annotation').append(textArea);
        annotationText.addClass('hide');

        var saveButton = $('<a class="b-sticky-button b-sticky-button_small js-saveAnnotation" href="#">Save</a>');

        var cancelButton = $('<a  class="b-sticky-button b-sticky-button_small b-sticky-button_colour_grey js-cancelAnnotation" href="#">Cancel</a>');

        annotation.append(saveButton);
        annotation.append(cancelButton);
        $(this).addClass('hide');
    });

    $('.js-saveAnnotation').live('click', function () {
        var sticky = $(this).parents('.b-note');
        var $newAnnotation = sticky.find('textarea.annotation-editable');
        var newAnnotationText = $newAnnotation[0].value;
        var $annotationText = sticky.find('.b-sticker__annotation span');
        $annotationText.text(newAnnotationText);

        $stickyNotes.stickyNotes("SaveAnnotationText", $annotationText.data('annotations-text'), newAnnotationText);

        sticky.find('.b-sticker__edit').removeClass('hide');
        $newAnnotation.text('');
        $newAnnotation.detach();
        sticky.find('.js-cancelAnnotation').detach();
        $(this).detach();
        $annotationText.removeClass('hide');
    });

    $('.js-cancelAnnotation').live('click', function () {
        var sticky = $(this).parents('.b-note');
        var annotationText = sticky.find('.b-sticker__annotation span');

        sticky.find('.b-sticker__edit').removeClass('hide');
        sticky.find('textarea.annotation-editable').detach();
        sticky.find('.js-saveAnnotation').detach();
        $(this).detach();
        annotationText.removeClass('hide');
    });

    $('.b-sticker__delete').live('click', function () {
        $stickyNotes.stickyNotes("DeleteAnnotation", $(this).data('annotations-id'));
        $(this).parent().parent().parent().detach();
    })

    $('.cms-js-saveAnnotationComment').live('click', function () {
        var sticky = $(this).parents('.b-sticker__comment');

        var $annotationComment = sticky.find('textarea.annotation-comment-editable');
        var commentText = $annotationComment[0].value;
        var $annotationText = sticky.find('.b-sticker__comment__text span');
        $annotationText.text(commentText);

        $stickyNotes.stickyNotes("SaveCommentText", $annotationText.data('annotation-comment-text'), commentText);

        $annotationComment.detach();
        sticky.find('.cms-js-cancelAnnotationComment').detach();
        $(this).detach();

        $annotationText.removeClass('hide');
        sticky.find('.b-sticker__comment__edit').removeClass('hide');
        sticky.find('.b-sticker__comment__delete').removeClass('hide');
        if ((sticky.parent().find('.b-sticker__comment').length > 1) && !(sticky.parent().hasClass('.b-sticker__body-with-comments '))) {
            sticky.parents('.b-sticker__body').addClass('b-sticker__body-with-comments');
        }

    });

    $('.cms-js-cancelAnnotationComment').live('click', function () {
        var sticky = $(this).parents('.b-sticker__comment');

        sticky.find('textarea.annotation-comment-editable').detach();
        sticky.find('.cms-js-saveAnnotationComment').detach();
        $(this).detach();

        sticky.find('.b-sticker__comment__text span').removeClass('hide');
        sticky.find('.b-sticker__comment__edit').removeClass('hide');
        sticky.find('.b-sticker__comment__delete').removeClass('hide');
        if ((sticky.parent().find('.b-sticker__comment').length > 1) && !(sticky.parent().hasClass('.b-sticker__body-with-comments ')))
            sticky.parents('.b-sticker__body').addClass('b-sticker__body-with-comments');

        var $annotationText = sticky.find('.b-sticker__comment__text span');
        $stickyNotes.stickyNotes("DeleteComment", $annotationText.data('annotation-comment-text'));
        sticky.detach();
    });

    $('.b-sticker__comment__delete').live('click', function () {
        $stickyNotes.stickyNotes("DeleteComment", $(this).data('annotation-comment-id'));
        if (($(this).parents('.b-sticker__comment').parent().find('.b-sticker__comment').length <= 2) && $(this).parents('.b-sticker__body').hasClass('b-sticker__body-with-comments')) {
            $(this).parents('.b-sticker__body').removeClass('b-sticker__body-with-comments');
        }
        $(this).parent().detach();
    });

    $('.b-sticker__comment__edit').live('click', function () {
        var sticky = $(this).parents('.b-sticker__comment');
        var $commentText = sticky.find('.b-sticker__comment__text span');
        var $textArea = $('<textarea class="annotation-comment-editable text">' + $commentText.text() + '</textarea>');
        $textArea.css({
            'width': sticky[0].scrollWidth - 30 + 'px'
        });
        var $comment = sticky.find('.b-sticker__comment__text').append($textArea);
        $commentText.addClass('hide');

        var $saveButton = $('<a class="b-sticky-button b-sticky-button_small cms-js-saveAnnotationComment" href="#">Save</a>');

        var $cancelButton = $('<a class="b-sticky-button b-sticky-button_small b-sticky-button_colour_grey cms-js-cancelAnnotationComment" href="#">Cancel</a>');

        $comment.append($saveButton);
        $comment.append($cancelButton);
        $(this).addClass('hide');
        sticky.find('.b-sticker__comment__delete').addClass('hide');
    });

});